﻿import java.awt.AWTException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class GuiBase extends JFrame implements ActionListener  {
	public int MAX_BUTTON = 9;
	public JButton jb[] = new JButton[MAX_BUTTON];
	public JLabel jl1 = new JLabel("-");
	public JLabel jl2 = new JLabel("");
	public JLabel jl3 = new JLabel("");
	public JLabel jl4 = new JLabel("");
	public JLabel jl5 = new JLabel("");
	public JLabel jl6 = new JLabel("");
	public JFrame frame;
	
	public JPanel panel_top;
	public JPanel panel_left;
	
	public static int iDelay = 11;
	public static String strLangEinsatz = "";
	public static String strURL1 = "";
	
	public static int iPort = 1;
	
	public JLabel jlIcon = new JLabel();
	public ImageIcon imageIcon = new ImageIcon();
	
	public javax.swing.Timer t = new javax.swing.Timer(iDelay, this);
	
	public GuiBase() {
		super();
		ComListener.debug("GuiBase", "DEBUG>> Version: V1.03");
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception err) {
			ComListener.debug("ANZEIGE",  "ERROR: " + err);
		}
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -8984932068374307167L;

	
	public void listen() {
		try {
			ServerSocket listen = new ServerSocket(iPort);
			while (true) {
				getConnection(listen.accept());
			}
		} catch (IOException err) {
			ComListener.debug("ANZEIGE",  "ERROR>> [TCPServer]: " + err.toString());
		}
	}
	
	/****
	 * Bewegt die Maus an die Postition 0,2000 (links unten) des Bildschirms, um
	 * den Bildschirmschoner anzuhalten
	 */
	private void moveMouse() {
		Robot robot;
		try {
			robot = new Robot();
			robot.mouseMove(0, 2000);
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}
	
	
	public void getConnection(Socket s) {
		BufferedReader in = null;
		String str = "", strGesamt = "", strMapService = "";
		String s1 = "", s2 = "", s3 = "", s4 = "", s5 = "", s6 = "", s7 = "", s8 = "", s9 = "", s10 = "", s11 = "", s12 = "", s13 = "", s9a ="", sX="";
		try {
			in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
			InetAddress ia = s.getInetAddress();
			ComListener.debug("ANZEIGE", "DEBUG>> IP-Adresse: " + ia.getHostAddress());
			ComListener.debug("ANZEIGE", "DEBUG>>  Host-Name: " + ia.getHostName());
			while ((str = in.readLine()) != null) {
				strGesamt = strGesamt + str;
			}
		} catch (IOException err) {
			ComListener.debug("ANZEIGE", "ERROR>> [TCPServer]: " + err.toString());
		} finally {
			try {
				in.close();
			} catch (IOException err) {
				ComListener.debug("ANZEIGE", "ERROR>> in.close(): " + err);
			}
			try {
				s.close();
			} catch (IOException err) {
				ComListener.debug("ANZEIGE", "ERROR>> s.close(): " + err);
			}
		}
		ComListener.debug("ANZEIGE", "DEBUG>> String: " + strGesamt);

		s1 = strGesamt.substring(0, strGesamt.indexOf(":"));
		s2 = strGesamt.substring(strGesamt.indexOf(":") + 1);

		ComListener.debug("ANZEIGE", "DEBUG>> s1: " + s1);
		ComListener.debug("ANZEIGE", "DEBUG>> s2: " + s2);
		//TODO
		moveMouse();
		
		while (s2.indexOf("**") != -1) {
			s2 = s2.substring(0, s2.indexOf("**") + 1) + " *" + s2.substring(s2.indexOf("**") + 2, s2.length());
			ComListener.debug("ANZEIGE", "DEBUG>> sx: " + s2);
		}

		try {
			StringTokenizer st2 = new StringTokenizer(s2, "*");
			s3 = st2.nextToken().trim(); // Datum
			s4 = st2.nextToken().trim(); // Stichwort
			s5 = st2.nextToken().trim(); // Stichwort Ergänzung
			s6 = st2.nextToken().trim(); // Objekt
			s7 = st2.nextToken().trim(); // Strasse
			s8 = st2.nextToken().trim(); // Strasse (nicht wichtig)
			s9 = st2.nextToken().trim(); // PLZ & Ort (nach Lst.)
			s9a = st2.nextToken().trim(); // Zusatz1
			s13 = st2.nextToken().trim(); // //Pat. Name

			StringTokenizer st3 = new StringTokenizer(s9, " ");
			s10 = st3.nextToken().trim(); // PLZ
			s13 = st2.nextToken().trim(); // Zusatz (Pat. Name)
		} catch (NoSuchElementException err) {
			ComListener.debug("ANZEIGE", "ERROR>> NoSuchElement (Falsche Formatierung der Nachricht?) " + err);
			s1 = "<Falsche Nachricht> - " + s1;
		}
		ComListener.debug("ANZEIGE", "DEBUG>>  s3: " + s3); //Datum Uhrzeit
		ComListener.debug("ANZEIGE", "DEBUG>>  s4: " + s4); //Stichwort
		ComListener.debug("ANZEIGE", "DEBUG>>  s5: " + s5); //Stichwort Ergänzung
		ComListener.debug("ANZEIGE", "DEBUG>>  s6: " + s6); //Objekt
		ComListener.debug("ANZEIGE", "DEBUG>>  s7: " + s7); //Strasse
		ComListener.debug("ANZEIGE", "DEBUG>>  s8: " + s8); //Strasse2
		ComListener.debug("ANZEIGE", "DEBUG>>  s9: " + s9); //PLZ Ort
		ComListener.debug("ANZEIGE", "DEBUG>> s9a: " + s9a); //Zusatz
		//ComListener.debug("ANZEIGE", "DEBUG>> s10: " + s10); //PLZ
		//ComListener.debug("ANZEIGE", "DEBUG>> s11: " + s11); //Ort_Ort
		//ComListener.debug("ANZEIGE", "DEBUG>> s12: " + s12); //Ort
		ComListener.debug("ANZEIGE", "DEBUG>> s13: " + s13); //Pat. Name

		Datenbank db = new Datenbank();
		strLangEinsatz = db.dbQueryFahrzeuge(s4, s9, jb);		// JButton setzen und Langtext des Einsatzes
		sX = db.dbQueryOrt(s4, s9);
		String sLat_Lon = db.slon_lat;
		String sxLat = "", sxLon = "", sX1="", sX2="";
		// Ansicht mit fiktivem Ort Lat/Lon)
		if (!sLat_Lon.equals("")) {
			StringTokenizer sLat_Lon2 = new StringTokenizer(sLat_Lon, ",");
			sxLat = sLat_Lon2.nextToken();
			sxLon = sLat_Lon2.nextToken();
			sX1 = s9;
			sX2 = s9a;
		} else {
			// Ansicht mit richtigem Ort
			StringTokenizer st5 = new StringTokenizer(sX, " ");
			sX1 = st5.nextToken();
			sX2 = st5.nextToken();
		
			
		}
		
		jl1.setText(s1 + " - " + s3);
		jl2.setText(s4 + " - " + strLangEinsatz);
//		if (s13.length() < 2) {
//			jl3.setText(s5);
//		} else {
//			jl3.setText(s5 + " - " + s9a);
//		}
		if (s13.length() > 2) {
			jl3.setText(s5 + ", " + s9a + ", " + s13);
		}
		jl4.setText(s6);
		jl5.setText(s7 + ", " + sX1 + " " + sX2);
		
		//
		// Karte erstellen
		//
		strMapService = db.dbQueryConfig("map_service");
		ComListener.debug("ANZEIGE", "DEBUG>> Starte Kartendienst... ");
		strURL1 = Kartendienst.kartenDienst(s7, sX1, sX2, strMapService, jlIcon, this, sxLat, sxLon);
		this.paint(this.getGraphics());

		// EMail versenden
		//
		//SendMail sm = new SendMail(strGesamt, s1);
		
		// Timer (re)starten
		//
		if (t.isRunning()==true) {
			t.restart();
		} else {
			t.start();				// Timer starten
		}
	}

	
	public void paint(Graphics g) {
		super.paint(g);
	}
	
	private void resetAnzeige() {
		for (int x=0; x < MAX_BUTTON; x++) {
			jb[x].setText("");
			jb[x].setBackground(Color.LIGHT_GRAY);
		}
		jl1.setText("-");
		jl2.setText("-");
		jl3.setText("-");
		jl4.setText("-");
		jl5.setText("-");
		imageIcon = new ImageIcon();
		jlIcon.setIcon(imageIcon);
		this.paint(this.getGraphics());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() instanceof JButton) {
			ComListener.debug("ANZEIGE", "DEBUG>> Button-Event, PDF erzeugen");
			try {
				Image i1 = new ImageIcon(new URL(strURL1)).getImage();
				PDFSchreiben ps = new PDFSchreiben();
				ps.initData(jl1.getText(), jl2.getText(), jl3.getText(), jl4.getText(), /*jl5.getText()*/"", i1,
						jb[0].getText(), jb[1].getText(), jb[2].getText(), jb[3].getText(), jb[4].getText(),
						jb[5].getText(), jb[6].getText(), jb[7].getText(), jb[8].getText(), Kartendienst.getFormatierterWeg());
				ps.createPdf("dada.pdf");
			} catch (Exception err) {
				ComListener.debug("ANZEIGE", "ERROR>> " + err);
			}
		}
		if (e.getSource() instanceof javax.swing.Timer) {
			ComListener.debug("ANZEIGE", "DEBUG>> Timer-Event, Anzeige leeren");
			t.stop();
			resetAnzeige();
		}
		
	}

}